package ar.edu.unq.tpi.uis.tepe3.wicket.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import ar.edu.unq.tpi.uis.tepe3.dominio.Access;
import ar.edu.unq.tpi.uis.tepe3.dominio.Folder;
import ar.edu.unq.tpi.uis.tepe3.dominio.Privilege;
import ar.edu.unq.tpi.uis.tepe3.dominio.User;
import ar.edu.unq.tpi.uis.tepe3.dominio.exception.PersistenceException;
import ar.edu.unq.tpi.uis.tepe3.wicket.AbstractFormPage;
import ar.edu.unq.tpi.uis.tepe3.wicket.WicketApplication;

/**
 * 
 * @author gpilla <gpilla@unq.edu.ar>
 *
 */
public class AccessForUserFormPage extends AbstractFormPage {

	protected IModel aHostModel;
	
	public AccessForUserFormPage(IModel aHostModel) {
		super("Crear nuevo acceso para usuario");
		this.aHostModel = aHostModel;
		
		setModel(new CompoundPropertyModel(new Access()));
		
		initializeForm(AccessListPage.class);
	}
	
	public AccessForUserFormPage(IModel aHostModel, IModel model) {
		super("Crear nuevo acceso para usuario", model);
		this.aHostModel = aHostModel;
		
		initializeForm(AccessListPage.class);
	}

	protected List<User> getGrantables() {
		return ((WicketApplication) getApplication()).getModel().getUsers();
	}
	
	protected List<Privilege> getPrivileges() {
		List<Privilege> candidates = new ArrayList<Privilege>();
		// Solo para convertirlo en una lista, no encontre una manera mas limpia (tampoco me tome mucho mas de 10min)
		for (Privilege privilege : Privilege.values()) {
			candidates.add(privilege);
		}
		return candidates;
	}
	
	@Override
	protected void addFields() {
		aForm.add(new FeedbackPanel("feedback"));
        aForm.add(new DropDownChoice("who", getGrantables()));
        aForm.add(new DropDownChoice("how", getPrivileges()));
	}

	@Override
	protected void saveAction() {
		try {
			System.out.println(((Access) getModelObject()).getWho());
			((Folder) aHostModel.getObject()).addAccess((Access) getModelObject());
			((WicketApplication) getApplication()).save();
			setResponsePage(new AccessListPage(aHostModel));
		} catch (Exception e) {
			warn(e.getMessage());
		}
	}
	
	@Override
	protected void addEditButton(){
		aForm.add(new Button("save") {
			
			@Override
			public void onSubmit() {
				saveAction();
			}
		});
	}
	
	@Override
	protected void addCancelButton(){
		aForm.add(new Link("cancel") {
			@Override
			public void onClick() {
				setResponsePage(new AccessListPage(aHostModel));
			}
		});
	}

}
